import { _commentList, _commentCount } from "../../service/api";

Page({
  data: {
    typeId: 0,
    valueId: null, // 商品ID
    page: 1,
    size: 20,
    showType: 0, // 显示类型
    commentList: [], // 评论列表
    showCommentList: [], // 显示的评论列表
    allCount: 0, // 没图总条数
    picCount: 0, // 有图总条数
    scrollY: 100,
  },
  onLoad: function (options) {
    this.setData({
      valueId: options.valueId,
      typeId: options.typeId,
    });
    this.initData();
  },
  async initData() {
    const { typeId, valueId, page, size, showType } = this.data;
    const list = await _commentList({ typeId, valueId, size, page, showType });
    const { count, picCount } = await _commentCount({ valueId, typeId });
    this.setData({ commentList: list, showCommentList: list, allCount: count, picCount });
  },
  // 切换
  handleSwitchTab() {
    this.setData({ showType: this.data.showType === 1 ? 0 : 1 });
    const { showType, commentList } = this.data;
    if (showType === 1) {
      let list = commentList.filter((item) => item.pic_list.length > 0);
      this.setData({ showCommentList: list, page: 1, scrollY: 0 });
    } else {
      this.setData({ showCommentList: commentList, page: 1, scrollY: 0 });
    }
  },
  // 上拉触底
  handleReachBottom() {
    this.setData({ page: this.data.page + 1 });
    const { page, showType, picCount, allCount } = this.data;
    if (showType === 1 && page <= Math.ceil(picCount / 20)) {
      this.getMoreComment();
    } else if (showType === 0 && page <= Math.ceil(allCount / 20)) {
      this.getMoreComment();
    }
  },
  // 获取更多评论
  async getMoreComment() {
    const { typeId, valueId, page, size, showType, showCommentList } = this.data;
    const list = await _commentList({ typeId, valueId, size, page, showType });
    this.setData({ showCommentList: [...showCommentList, ...list] });
  },
});
